<template>
  <div class="app-container">
    <el-row>
      <el-col :span="2">
        <label class="row-label">业务操作</label>
      </el-col>
      <el-col
        class="align-right"
        :span="22"
      >
        <el-button-group>
          <el-button
            v-permission="'ADD'"
            type="primary"
            icon="el-icon-plus"
            @click="handleCreate"
          >
            {{ $t('table.add') }}
          </el-button>
          <el-button
            v-permission="'MODIFY'"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate"
          >
            {{ $t('table.edit') }}
          </el-button>
          <el-button
            v-permission="'DELETE'"
            type="primary"
            icon="el-icon-delete"
            class="deleted-button"
            @click="handleDelete"
          >
            {{ $t('table.delete') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            class="refresh-button"
            @click="handleRefresh"
          >
            {{ $t('tagsView.refresh') }}
          </el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <div style="height: 600px;width: 100%">
      <pl-table
        :ref="tableRef"
        v-loading="listLoading"
        :data="list"
        use-virtual
        record-table-select
        :row-height="42"
        :pagination-show="false"
        border
        fit
        highlight-current-row
        header-row-class-name="table-header"
        cell-class-name="table-cell"
        style="width: 100%;"
        @row-click="handelRowClick"
        @row-dblclick="handleUpdate"
        @current-change="handleCurrentRowChange"
      >
        <pl-table-column
          label="编码"
          prop="groupCode"
          align="center"
          sortable
          :filters="columnFilters.groupCode"
          :filter-method="columnFilterHandler"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.groupCode }}</span>
          </template>
        </pl-table-column>
        <pl-table-column
          label="名称"
          prop="groupName"
          min-width="150px"
          align="center"
          sortable
          :filters="columnFilters.groupName"
          :filter-method="columnFilterHandler"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.groupName }}</span>
          </template>
        </pl-table-column>
      </pl-table>
    </div>
    <!-- 新增修改 -->
    <el-dialog
      :title="$t('route.group') + '--' + $t('table.'+ dialogStatus)"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      custom-class="dialog-title-background"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="名称"
          prop="groupName"
        >
          <el-input
            v-model="temp.groupName"
            placeholder="请输入名称"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          class="pause-button"
          @click="handleCancel"
        >
          {{ $t('table.cancel') }}
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='add'?createData():updateData()"
        >
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getList, addOne, updateOne, deleteItem } from '@/api/basic-data'
export default {
  name: 'Group',
  components: {
  },
  data() {
    return {
      filterCondition: {
        dateRange: ''
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      tableRef: 'dataTable',
      list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      temp: {
        groupCode: undefined,
        groupName: undefined
      },
      currentRow: null,
      dialogFormVisible: false,
      allotDialogVisible: false,
      dialogStatus: 'add',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      downloadLoading: false
    }
  },
  computed: {
    rules: function () {
      return {
        groupName: [{ required: true, message: '请输入名称', trigger: 'change' }]
      }
    },
    columnFilters: function () {
      return {
        groupCode: this.list.map(item => {
          return {
            text: item.groupCode,
            value: item.groupCode
          }
        }).filter((element, index, self) => { // 去重
          return self.findIndex(el => el.value === element.value) === index
        }),
        groupName: this.list.map(item => {
          return {
            text: item.groupName,
            value: item.groupName
          }
        }).filter((element, index, self) => { // 去重
          return self.findIndex(el => el.value === element.value) === index
        })
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const res = await getList('group', {})
      this.list = res.data.pageItems
      this.listLoading = false
    },
    setTemp(tmp) {
      this.temp = {
        groupCode: tmp.groupCode,
        groupName: tmp.groupName
      }
    },
    resetTemp() {
      this.temp = {
        groupCode: undefined,
        groupName: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate() {
      // const getPermissionOperations = store.getters && store.getters.getPermissionOperations
      // const operations = getPermissionOperations(router.currentRoute.name)
      // if (!operations.includes('MODIFY')) {
      //   return
      // }
      if (!this.currentRow) {
        this.$message({
          showClose: true,
          message: '请选择一条记录',
          type: 'warning',
          center: true
        })
        return
      }
      this.setTemp(this.currentRow)
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCancel() {
      this.$confirm('是否放弃保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
        this.resetTemp()
        this.$refs['dataForm'].setCurrentRow()
      }).catch(() => {
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          const res = await addOne('insertGroup', this.temp)
          if (res) {
            this.$refs['dataForm'].resetFields()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.resetTemp()
          }
        } else {
          return false
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          this.temp.groupCode = this.currentRow.groupCode
          const res = await updateOne('updateGroup', this.temp)
          if (res) {
            this.$refs['dataForm'].resetFields()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
          this.getList()
          this.resetTemp()
        }
      })
    },
    handleDelete() {
      if (!this.temp.groupCode) {
        this.$message({
          showClose: true,
          message: '请选择一条记录',
          type: 'warning',
          center: true
        })
        return
      }
      this.$confirm('确认要删除该行吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteItem('deleteGroup', { groupCode: this.temp.groupCode })
        if (res) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
        this.getList()
        this.resetTemp()
      }).catch(() => {
      })
    },
    handleRefresh() {
      this.getList()
      this.resetTemp()
    },
    handelRowClick(row, column, event) {
      this.setTemp(row)
    },
    handleCurrentRowChange(row) {
      this.currentRow = row
    },
    columnFilterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    }
  }
}
</script>

<style lang="scss">
</style>
